

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;


/**
 * Utility class used to Parse image files and solution files 
 *
 */
public final class FileParser {

	public static ArrayList<Image> parseImageFile(String imageFile) {
		ArrayList<Image> imageArray = new ArrayList<Image>();
		try {

			Image currentImage = null;
			int nbRowRead = -1;
			FileInputStream in = new FileInputStream(imageFile);
			BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
			String line = "";
			while ((line = br.readLine()) != null) {
				if (line.startsWith("#")) {
					//System.out.println("Ignoring comment : " + line);
				}
				else if (line.matches("^[a-zA-Z].*")) {
					// File name
					if (nbRowRead == -1) {
						nbRowRead = 0;
						currentImage = new Image(line);
					}
					else {
						//System.out.println("Incorrect syntax : Expecting file name");
					}
				}
				else if (line.matches("^[0-9].*")) {
					// image row
					if (nbRowRead != -1) {
						Scanner scanner = new Scanner(line);
						int nbValue = 0;
						while(nbValue < Image.IMAGE_WIDTH) {
							currentImage.setPixelValue(scanner.nextInt(), nbRowRead, nbValue);
							nbValue++;
						}
						nbRowRead++;
						if (nbRowRead == Image.IMAGE_HEIGHT) {
							// Image fully read, adding it to the list and reseting parameters
							imageArray.add(currentImage);
							currentImage = null;
							nbRowRead = -1;
						}
					}
					else {
						//System.out.println("Incorrect syntax : Expecting image row");
					}
				}
				else {
					//System.out.println("Unrecognized line : ");
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return imageArray;
	}

	public static void readMoodFile(String moodFile, ArrayList<Image> imageList) {
		try {
			FileInputStream in = new FileInputStream(moodFile);
			BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
			String line = "";
			int imgNumber = 0;
			while ((line = br.readLine()) != null && imgNumber < imageList.size()) {
				if (line.startsWith("#")) {
					//System.out.println("Ignoring comment : " + line);
				}
				else {
					String[] splitResult = line.split(" ");
					if (splitResult.length == 2 ) {
						// Image should be in the same order
						assert (imageList.get(imgNumber).getName().equals(splitResult[0]));
						imageList.get(imgNumber).setMood(Image.int2Mood(Integer.valueOf(splitResult[1])));
						imgNumber++;
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
